<template>
    <div class="main">
        <div class="filter-container">
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoods">添加商品</el-button>
            <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoodsPackage" plain>添加套餐</el-button>
            <el-button v-if="form.specialTopicGoodsList.length>8"  type="success" class="filter-item fr" @click="save">保 存</el-button>
        </div>
        <el-form :model="form" size="medium" ref="form" label-width="0px">
            <el-table :data="form.specialTopicGoodsList" v-loading="listLoading" element-loading-text="给我一点时间">
                <el-table-column align="center" type="expand" width="100">
                    <template slot-scope="scope" v-if="scope.row.type===1 && scope.row.goodsAttr.filter(item=>item.deleteFlag!==0).length">
                        <el-table :data="scope.row.goodsAttr.filter(item=>item.deleteFlag!==0)" highlight-current-row border>
                            <el-table-column v-for="(item, index) in [{id: 'attrId1',prop: 'attrValue1'},{id:'attrId2',prop: 'attrValue2'},{id:'attrId3',prop: 'attrValue3'},{id:'attrId4',prop: 'attrValue4'},{id:'attrId5',prop: 'attrValue5'},{id:'attrId6',prop: 'attrValue6'}]" v-if="scope.row.goodsAttr[0][item.id]" :key="index" align="center" :label="'属性值'+(index+1)" :prop="item.prop" min-width="100px">
                            </el-table-column>
                            <!--<el-table-column align="center" label="财务价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].financePrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.financePrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="成本价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].costPrice'" :rules="commonRules.priceRuleNull" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.costPrice" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="市场价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].marketValue'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.marketValue" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="兰蜜价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].price'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.price" style="width: 100%" @change="calcOtherPrice(scope.$index, $scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="大区价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].regionPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.regionPrice" style="width: 100%" placeholder="自动生成" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="董事价" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].directorPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.directorPrice" style="width: 100%" placeholder="自动生成" disabled></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <!--<el-table-column align="center" label="佣金类型">
                                <template slot-scope="$scope">
                                    <el-select v-model="$scope.row.commissionType" style="width: 100%">
                                        <el-option :key="1" label="数值(元)" :value="1"></el-option>
                                        <el-option :key="2" label="比例(%)" :value="2"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="佣金数值" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].commission'" :rules="$scope.row.commissionType===1?commonRules.priceRule : commonRules.percentRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.commission" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="最高佣金" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].maximumCommission'" :rules="commonRules.priceRuleZero" style="margin: 30px 0">
                                        <el-input type="number" placeholder="小于兰蜜价" v-model="$scope.row.maximumCommission" style="width: 100%" @change="calcOtherPrice(scope.$index, $scope.$index)"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="库存数" min-width="90px">
                                <template slot-scope="$scope">
                                    可分配：{{$scope.row.totalSkuNumber}}<br/>
                                    已分配：{{($scope.row.distributedSkuNumber||0)+($scope.row.soldNumber||0)}}<br/>
                                    <el-form-item v-if="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].skuNumber'" :rules="commonRules.skuNumberRule" style="margin-bottom: 30px">
                                        <el-input-number v-model="$scope.row.skuNumber" :min="1" :max="$scope.row.totalSkuNumber+($scope.row.distributedSkuNumber||0)" :precision="0" :controls="false" style="width: 100%"></el-input-number>
                                    </el-form-item>
                                    <span v-else style="color: red">库存不足</span>
                                </template>
                                <!--<template slot-scope="$scope">
                                    剩余库存：{{$scope.row.totalSkuNumber}}<br/>
                                    <el-input-number v-if="$scope.row.totalSkuNumber" v-model="$scope.row.skuNumber" :min="1" :max="$scope.row.totalSkuNumber" :precision="1" :controls="false" style="width: 100%"></el-input-number>
                                    <span v-else style="color: red">库存不足</span>
                                </template>-->
                                <!--<template slot-scope="$scope">
                                    <el-input type="number" v-model="$scope.row.skuNumber"></el-input>
                                </template>-->
                            </el-table-column>
                            <!--<el-table-column align="center" label="数量" min-width="70px">
                                <template slot-scope="$scope">
                                    <el-form-item :prop="'specialTopicGoodsList.'+scope.$index+'.goodsAttr['+$scope.$index+'].number'" :rules="commonRules.numberRule" style="margin: 30px 0">
                                        <el-input type="number" v-model="$scope.row.number" style="width: 100%"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>-->
                            <el-table-column align="center" label="是否上架" width="80">
                                <template slot-scope="$scope">
                                    <el-switch
                                            v-model="$scope.row.upshelf"
                                            active-color="#13ce66"
                                            inactive-color="#ff4949"
                                            :active-value="1"
                                            :inactive-value="0">
                                    </el-switch>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="操作" width="60" fixed="right" v-if="scope.row.goodsAttr.filter(item=>item.deleteFlag!==0).length>1">
                                <template slot-scope="$scope">
                                    <a href="javascript: void(0);" class="el-icon-remove" @click="delAttr(scope.$index, $scope.$index)"></a>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="类型" width="120">
                    <template slot-scope="scope">
                        <span v-text="itemTypes[scope.row.type-1]"></span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="名称">
                    <template slot-scope="scope">
                        <a style="color: #409eff" target="_blank" :href="getUrl({id: scope.row.goodsId || scope.row.packageId, fromType: 5, goodsType: scope.row.type, activityId: scope.row.topicId, packType: ''})">
                            {{scope.row.type ===1 ? scope.row.goodsName: scope.row.packageName}}
                        </a>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="用户限购数量【0代表不限购】" width="220">
                    <template slot-scope="scope">
                        <el-form-item :prop="'specialTopicGoodsList['+scope.$index+'].userQuantity'" :rules="commonRules.skuNumberRule" style="margin-top: 22px">
                            <el-input v-model="scope.row.userQuantity" style="width: 100%;"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <!--<el-table-column align="center" label="是否启用">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="2">
                        </el-switch>
                    </template>
                </el-table-column>-->
                <!-- <el-table-column align="center" label="排序" width="120">
                    <template slot-scope="scope">
                        <el-input type="number" v-model="scope.row.sort"></el-input>
                    </template>
                </el-table-column>-->
                <el-table-column align="center" label="操作" width="120" fixed="right">
                    <template slot-scope="scope">
                        <a href="javascript: void(0);" class="el-icon-remove" @click="delItem(scope.row, scope.$index)"></a>
                    </template>
                </el-table-column>
            </el-table>
            <div style="text-align: center; padding: 20px">
                <el-button type="success" @click="save">保 存</el-button>
            </div>
        </el-form>
    </div>
</template>
<script>
  import differenceBy from 'lodash/differenceBy';
  export default {
    name: 'activitySecKillGoodsList',
    props: {
      id: {
        default: ''
      }
    },
    data(){
      return {
        itemTypes: ['商品', '套餐'],
        listLoading: false,
        listQuery: {
          id: this.id,
          userId: this.$store.getters.userId
        },
        form: {
          specialTopicGoodsList: [],
          goodsAttr: [],
        },
        tempGoodsCheck: [],
        tempPackageChecked: []
      }
    },
    created(){
      this.getList();
    },
    methods: {
      getList(){
        this.listLoading = true;
        this.request({
          url: '/bsnl-activity/specialTopicGoods/details',
          method: 'get',
          params: this.listQuery
        }).then(({data, totalCount}) => {
          console.log(data);
          if(data){
            this.form = data;
            this.form.goodsAttr.map(item => {
              item.distributedSkuNumber = item.skuNumber
            });
            this.tempGoodsCheck = [];
            this.tempPackageChecked = [];
            this.form.specialTopicGoodsList.map(item => {
              if(item.type===1){
                this.tempGoodsCheck.push({
                  id: item.goodsIdId,
                  goodsId: item.goodsId,
                  name: item.goodsName
                });
                item.goodsAttr = this.form.goodsAttr.filter(subItem => item.goodsId === subItem.goodsId );
              }
              else if(item.type === 2){
                this.tempPackageChecked.push({
                  packageId: item.packageId,
                  name: item.packageName
                })
              }
            });
          }
          this.listLoading = false;
        }).catch(err => {
          console.log(err);
          this.listLoading = false;
        });
      },
      // 选择商品
      chooseGoods(){
        this.checkGoods(this.tempGoodsCheck).then(val => {
          let goodsList = this.form.specialTopicGoodsList.filter(item => item.type ===1);
          let needDelGoods = differenceBy(goodsList, val, 'goodsId');
          let needAddGoods = differenceBy(val, goodsList, 'goodsId');
          let ids = [];
          needDelGoods.map(item => {
            if(item.id){
              ids.push({id: item.id});
            }
          });

          if(ids.length){
            this.request({
              url: '/bsnl-activity/specialTopicGoods/status',
              method: 'post',
              data: {ids}
            }).then(() => {
              this.form.specialTopicGoodsList = (differenceBy(this.form.specialTopicGoodsList, needDelGoods, 'goodsId'));
            }).catch(err => {
              console.log(err);
            });
          }
          else{
            this.form.specialTopicGoodsList = (differenceBy(this.form.specialTopicGoodsList, needDelGoods, 'goodsId'));
          }
          needAddGoods.map((item) => {
            this.request({
              url: '/bsnl-product/goods/details',
              method: 'get',
              params: {
                id: item.id,
                userId: this.$store.getters.userId
              }
            }).then(({data}) => {
              let { goodsAttr } = data;
              goodsAttr.map(item=> {
                item.skuNumber=1;
                item.number=1;
              });
              this.form.specialTopicGoodsList.push({
                goodsId: item.goodsId,
                goodsName: item.name,
                type: 1,
                status: 1,
                topicId: this.id,
                jumpId: item.goodsId,
                id: null,
                userQuantity: 0,
                goodsAttr
              });
            });
          });
        }).catch(err => {
          this.tempGoodsCheck = [];
          this.form.specialTopicGoodsList = this.form.specialTopicGoodsList.filter(item => item.type !==1);
        });
      },
      // 选择套餐
      chooseGoodsPackage(){
        this.checkPackage(this.tempPackageChecked).then(val => {
          this.tempPackageChecked = [...val];
          let packageList = this.form.specialTopicGoodsList.filter(item => item.type ===2);
          let needDelPackage = differenceBy(packageList, val, 'packageId');
          let needAddPackage = differenceBy(val, packageList, 'packageId');

          let ids = [];
          needDelPackage.map(item => {
            if(item.id){
              ids.push({id: item.id});
            }
          });

          if(ids.length){
            this.request({
              url: '/bsnl-activity/specialTopicGoods/status',
              method: 'post',
              data: {ids}
            }).then(() => {
              this.form.specialTopicGoodsList = (differenceBy(this.form.specialTopicGoodsList, needDelPackage, 'packageId'));
            }).catch(err => {
              console.log(err);
            });
          }
          else{
            this.form.specialTopicGoodsList = (differenceBy(this.form.specialTopicGoodsList, needDelPackage, 'packageId'));
          }

          needAddPackage.map((item) => {
            this.form.specialTopicGoodsList.push({
              topicId: this.id,
              type: 2,
              status: 1,
              userQuantity: 0,
              packageId: item.packageId,
              jumpId: item.packageId,
              packageName: item.name
            });
          });
          /*
          this.form.specialTopicGoodsList = this.form.specialTopicGoodsList.filter(item => {
              return item.type === 1;
          });
          val.map(item => {
              this.form.specialTopicGoodsList.push({
                  crushId: this.id,
                  type: 2,
                  status: 1,
                  packageId: item.id,
                  packageName: item.name
              });
          });*/
        }).catch(err => {
          this.tempPackageChecked = [];
        });
      },
      delItem(row, index){
        console.log(row, 555);
        this.$confirm(row.id?`该删除将直接从数据库删除，确定要删除吗?`:`确定要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(row.id){
            this.request({
              url: '/bsnl-activity/specialTopicGoods/status',
              method: 'post',
              data: {
                ids: [{id: row.id}],
              }
            }).then(({data, totalCount}) => {
              this.form.specialTopicGoodsList.splice(index, 1);
              if(row.type ===1){
                this.tempGoodsCheck.splice(this.tempGoodsCheck.findIndex(item => {return item.goodsId === row.goodsId}), 1);
              }
              else if(row.type ===2){
                this.tempPackageChecked.splice(this.tempPackageChecked.findIndex(item => {return item.packageId === row.packageId}), 1);
              }
              this.$message.success('删除成功');
            }).catch(err => {
              console.log(err);
            });
          }
          else{
            this.form.specialTopicGoodsList.splice(index, 1);
            if(row.type ===1){
              this.tempGoodsCheck.splice(this.tempGoodsCheck.findIndex(item => {return item.goodsId === row.goodsId}), 1);
            }
            else if(row.type ===2){
              this.tempPackageChecked.splice(this.tempPackageChecked.findIndex(item => {return item.packageId === row.packageId}), 1);
            }
            this.$message.success('删除成功');
          }
        }).catch(err => {
          console.log(err);
        });
      },
      delAttr(itemIndex, attrIndex){
        this.$confirm(`确定要删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.specialTopicGoodsList[itemIndex].goodsAttr.filter(item=>item.deleteFlag!==0)[attrIndex].deleteFlag=0;
          /*let length = this.form.specialTopicGoodsList[itemIndex].goodsAttr.length;
          if(length>1){
              this.form.specialTopicGoodsList[itemIndex].goodsAttr.splice(attrIndex, 1);
          }
          else{
              this.tempGoodsCheck.splice(this.tempGoodsCheck.findIndex(item => {return item.goodsId === this.form.specialTopicGoodsList[itemIndex].goodsId}), 1);
              this.form.specialTopicGoodsList.splice(itemIndex, 1);
          }
          this.$message.success('删除成功');*/
        }).catch(err => {
          console.log(err);
        });
      },
      // 根据兰蜜价和最高佣金计算大区价和董事价
      calcOtherPrice(index, subIndex){
        let query = {
          lmPrice: this.form.specialTopicGoodsList[index].goodsAttr[subIndex].price,
          highestCommission: this.form.specialTopicGoodsList[index].goodsAttr[subIndex].maximumCommission
        };
        this.calcRDPrice(query, (data) => {
          this.form.specialTopicGoodsList[index].goodsAttr[subIndex].regionPrice = data.regionPrice;
          this.form.specialTopicGoodsList[index].goodsAttr[subIndex].directorPrice = data.directorPrice;
        });
      },
      save(){
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false;
          }

          this.form.goodsAttr = [];
          let noSkuGoods = [];
          let skuNumFlag = false;
          let priceFlag = false;
          this.form.specialTopicGoodsList.map(item => {
            if(item.type ===1 && item.goodsAttr.length){
              item.goodsAttr.map(subItem => {
                if(!(subItem.totalSkuNumber+(subItem.distributedSkuNumber||0)) && subItem.deleteFlag && subItem.upshelf){
                  skuNumFlag = true;
                }
                if(!(subItem.marketValue>0 && subItem.price>0) && subItem.deleteFlag && subItem.upshelf){
                  priceFlag = true;
                }
                this.form.goodsAttr.push({
                  ...subItem,
                  associationId: this.id
                })
              })
            }
            else if(item.type ===1 && !item.goodsAttr.length){
              noSkuGoods.push(item)
            }
          });
          // console.log(this.form);
          if(skuNumFlag){
            this.$message.warning('存在0库存的规格商品，请先移除再保存');
          } else if(!noSkuGoods.length){
            this.request({
              url: '/bsnl-activity/specialTopicGoods/create',
              method: 'post',
              data: this.form
            }).then(() => {
              this.$message.success('保存成功');
              this.$router.back();
            }).catch(err => {
              console.log(err);
            });
          } else {
            let msg = '商品【';
            noSkuGoods.map((item, index) => {
              msg+=item.goodsName;
              msg+=(index===noSkuGoods.length-1?'】没有SKU信息，请先移除对应的商品':'、');
            });
            this.$message({
              message: msg,
              type: 'warning'
            });
          }
        });
      }
    }
  }
</script>
<style>
    .el-table__expanded-cell[class*=cell] {
        padding: 20px;
    }
    .el-table__body .el-select,
    .el-table__body .el-input{
        width: 100% !important;
    }
</style>
